package tech.yqyl.solo.processor;

import cn.hutool.core.text.StrFormatter;
import com.google.common.base.Splitter;
import tech.yqyl.StringUtil;
import tech.yqyl.halo.HaloMarkdownBoot;
import tech.yqyl.solo.BlogInfo;
import tech.yqyl.solo.BlogProcessor;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @className: BlogHeadProcessor
 * @description:
 * @author: caoyangjie
 * @date: 2024/9/5
 **/
public class BlogHeadProcessor extends AbstractProcessor implements BlogProcessor {
    @Override
    public boolean filter() {
        return !metaConfig.isWriteFile();
    }

    @Override
    public void process(BlogInfo blog) {
        List<String> contents = Splitter.on("\n").trimResults().omitEmptyStrings().splitToList(blog.getArticle().getArticleContent());
        List<String> modifys = new ArrayList<>();
        modifys.addAll(contents);
        boolean remove = false;
        if( modifys.size()>=3 ) {
            if( modifys.get(0).contains("已发布在个人微信公众号") ) {
                modifys.remove(0);
                remove = true;
            }
            if( modifys.get(remove?0:1).contains("更多精彩文章第一时间在公众号发布") ) {
                modifys.remove(remove?0:1);
            } else {
                remove = false;
            }
            if( modifys.get(remove?0:1).contains("https://gitee.com/caoyangjie/pictures") || modifys.get(2).contains("blog.yqyl.tech/") ) {
                modifys.remove(remove?0:1);
            }
            if( modifys.get(0).contains("https://gitbook.luckycxy.com/pictures/images/includes/") ) {
                modifys.remove(0);
            }
        }
        blog.getArticle().setArticleContent(modifys.stream().collect(Collectors.joining("\n")));
        String headContent = formatHeadContent(blog.getArticle().getFirstTag(), blog.getArticle().getArticleTitle(), blog.getArticle().getOId(), blog.isReadmeFlag());
        blog.push(headContent, convertMarkdownToHtml(headContent));
    }

    private String formatHeadContent(String tag, String title, String oid, boolean readme) {
        String headTemplate = "| 欢迎关注 |\n" +
                "|:----:|\n" +
                "| [【{}】]({}/archives/{}) |\n" +
                (!readme ? "| [【{}】]({}/archives/{}) |\n":"") +
                "| 已发布在个人微信公众号【猿起源落】，对文章进行了精简优化，欢迎大家关注! |\n" +
                "| ![关注二维码](https://gitbook.luckycxy.com/images01/images/20240904/4021061.png) |\n";
        if( readme ) {
            return StrFormatter.format(headTemplate,
                    tag, HaloMarkdownBoot.server.getDomain(), StringUtil.hashString(title)
            );
        }
        return StrFormatter.format(headTemplate,
                tag, HaloMarkdownBoot.server.getDomain(), StringUtil.hashString(tag.contains("系列")?tag:tag.concat("系列文章")),
                title, HaloMarkdownBoot.server.getDomain(), oid
        );
    }

    private String convertMarkdownToHtml(String markdown) {
        StringBuilder htmlBuilder = new StringBuilder();
        String[] lines = markdown.split("\n");

        // 处理表头
        if (lines.length > 0) {
            htmlBuilder.append("<div class=\"table-wrapper\"><table>\n<thead>\n<tr>\n<th align=\"center\">")
                    .append(lines[0].split("\\|")[1].trim())
                    .append("</th>\n</tr>\n</thead>\n<tbody>\n");
        }

        // 处理表格内容
        for (int i = 2; i < lines.length; i++) {
            String[] columns = lines[i].split("\\|");
            if (columns.length > 1) {
                String link = columns[1].replaceAll("(<img.*?>)", "<img src=\"$1\" alt=\"关注二维码\">");

                // 添加表格行
                htmlBuilder.append("<tr>\n<td align=\"center\">")
                        .append(StringUtil.md2Html(link.trim()))
                        .append("</td>\n</tr>\n");
            }
        }

        htmlBuilder.append("</tbody>\n</table>\n</div>");
        return htmlBuilder.toString();
    }
}
